package cn.tedu.store.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import cn.tedu.store.controller.ex.FileEmptyException;
import cn.tedu.store.controller.ex.FileSizeException;
import cn.tedu.store.controller.ex.FileTypeException;
import cn.tedu.store.controller.ex.FileUploadIoException;
import cn.tedu.store.controller.ex.FileUploadStateException;
import cn.tedu.store.entity.User;
import cn.tedu.store.service.IUserService;
import cn.tedu.store.util.JsonResult;

@RestController   //表示一个控制器类且所有请求结果响应正文
@RequestMapping("users")
public class UserController extends BaseController {
	private static final long AVATAR_MAX_SIZE = 1*1024*1024;
	private static final List<String> AVATAR_CONTENT_TYPES = new ArrayList<>();
	//初始化文件类型AVATAR_CONTENT_TYPES
	static {
		AVATAR_CONTENT_TYPES.add("image/jpeg");
		AVATAR_CONTENT_TYPES.add("image/png");
	}
	@Autowired 
    private IUserService userService;
	
	@RequestMapping("reg")
	public JsonResult<Void> reg(User user){
		
		userService.reg(user);
		//JsonResult<Void> jr=new  JsonResult<Void>();
		//jr.setState(1);
		//return jr;
		return new  JsonResult<Void>(SUCCESS);
	
	}
	
	@RequestMapping("login")
	public JsonResult<User> login(String username, String password,HttpSession session){
		User user=userService.login(username, password);
		session.setAttribute("uid", user.getUid());
		session.setAttribute("username", user.getUsername());
		return new  JsonResult<>(SUCCESS,user);
		
	}
	
	
	@RequestMapping("change_password")
	public JsonResult<Void> changePassword(
			@RequestParam("old_password") String oldPassword,
			@RequestParam("new_password") String newPassword,
			HttpSession session
			){
		Integer uid=Integer.valueOf(session.getAttribute("uid").toString());
		String username=session.getAttribute("username").toString();
		userService.changPassword(uid, username, oldPassword, newPassword);
		return new  JsonResult<>(SUCCESS);
	}
	
	
	
	@PostMapping("change_avatar")
	public JsonResult<String>  changeAvatar(
	HttpServletRequest request,
	@RequestParam("file") MultipartFile file) {
	if (file.isEmpty()) {
		throw new FileEmptyException("文件大小为空或不存在");
	}
	
	if (file.getSize()>AVATAR_MAX_SIZE) {
		//System.err.println(file.getSize());
		throw new FileSizeException("文件大小超过"+AVATAR_MAX_SIZE/1024+"KB限值");
	}
	
	if (!AVATAR_CONTENT_TYPES.contains(file.getContentType())) {
		throw new FileTypeException("文件类型不匹配，需要："+AVATAR_CONTENT_TYPES);
	}
	
	//确定文件夹
	String dirPath=request.getServletContext().getRealPath("upload");
	File dir=new File(dirPath);
	if(!dir.exists()){
	    dir.mkdirs();
	}
	//确定文件名
	String originalFilename=file.getOriginalFilename();
	String suffix="";
	int beginIndex=originalFilename.lastIndexOf(".");
	if( beginIndex!=-1){
	suffix=originalFilename.substring(beginIndex);
	}
	String filename=UUID.randomUUID().toString()+suffix;
	File dest=new File(dir,filename);
	//保存文件
	try {
		file.transferTo(dest);
	} catch (IllegalStateException e) {
		//e.printStackTrace();
		throw new FileUploadStateException("检查文件是否存在或移除");
	} catch (IOException e) {
		//e.printStackTrace();
		throw new FileUploadIoException("上传其他未知异常");
	}
	//持久层保存文件路径
	String avatar="/upload/"+filename;
	HttpSession session=request.getSession();
	Integer uid=getUidFromSession(session);
	String username=getUsernameFromSession(session);
	userService.changeAvatar(uid,username,avatar);

	JsonResult<String> js=new JsonResult<String>();
	js.setState(SUCCESS);
	js.setData(avatar);
	return js;
	}
	
	
	
	@GetMapping("get_info")
	public JsonResult<User> getByUid(HttpSession session){
		//Integer uid=Integer.valueOf(session.getAttribute("uid").toString());
		Integer uid=getUidFromSession(session);
		String username=session.getAttribute("username").toString();
		User data=userService.getByUid(uid);
		return new JsonResult<>(SUCCESS,data);
	}
	
	@RequestMapping("change_info")
	public JsonResult<Void> changeInfo(User user,HttpSession session){
		//Integer uid=Integer.valueOf(session.getAttribute("uid").toString());
		Integer uid=getUidFromSession(session);
		user.setUid(uid);
		user.setModified_user("lcc82323");
		userService.changeInfo(user);
		return new JsonResult<>(SUCCESS);
	}
}
